package com.zirenx.sys.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.upload.UploadFile;
import com.zirenx.common.config.ConstantConfig;
import com.zirenx.sys.model.SysFile;
import com.zirenx.sys.model.SysUser;
import com.zirenx.utils.DateUtils;
import com.zirenx.utils.FileUtils;
import com.zirenx.utils.ImageUtils;
import com.zirenx.utils.SysUserUtils;

public class SysUserService {
	private static final Log log = Log.getLog(SysUserService.class);
	
	private SysUser dao = new SysUser().dao();
	
	@Inject
	SysFileService sysFileService;
	
	public SysUser login(String username) {
		List<SysUser> list = dao.find("select * from sys_user t where username = ?", username);
		if(list!=null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	public Page<SysUser> paginate(int pageNumber, int pageSize, Kv kv) {
		StringBuffer sb = new StringBuffer("select * from sys_user t where 1=1 ");
		
		SqlPara sqlPara = new SqlPara();
		String name = kv.getStr("name");
		if(!StringUtils.isEmpty(name)) {
			sb.append(" and t.name = ?");
			sqlPara.addPara(name);
		}
		String deptId = kv.getStr("deptId");
		if(!StringUtils.isEmpty(deptId)) {
			sb.append(" and t.dept_id = ?");
			sqlPara.addPara(deptId);
		}
		sqlPara.setSql(sb.toString());
		
		return dao.paginate(pageNumber, pageSize, sqlPara);
	}
	
	public SysUser findById(String id) {
		return dao.findById(id);
	}

	public void delete(String id) {
		dao.deleteById(id);
	}

	public void batchRemove(String[] ids) {
		if(ids!=null) {
			for (String id : ids) {
				if(id!=null) {
					delete(id);
				}
			}
		}
	}

	/**
	 * 上传头像
	 * @param uploadFile
	 * @param avatarData
	 * @param userId
	 * @param request 
	 * @throws Exception
	 */
	public void uploadImg(UploadFile uploadFile, String avatarData, Long userId, HttpServletRequest request) throws Exception {
		SysFile sysFile = sysFileService.saveFile(uploadFile.getFileName(),"用户头像");
		String fileName = uploadFile.getFileName();
		
        //获取图片后缀
        String prefix = fileName.substring((fileName.lastIndexOf(".") + 1));
        String[] str = avatarData.split(",");
        //获取截取的x坐标
        int x = (int) Math.floor(Double.parseDouble(str[0].split(":")[1]));
        //获取截取的y坐标
        int y = (int) Math.floor(Double.parseDouble(str[1].split(":")[1]));
        //获取截取的高度
        int h = (int) Math.floor(Double.parseDouble(str[2].split(":")[1]));
        //获取截取的宽度
        int w = (int) Math.floor(Double.parseDouble(str[3].split(":")[1]));
        //获取旋转的角度
        int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));
        try {
            BufferedImage cutImage = ImageUtils.cutImage(new FileInputStream(uploadFile.getFile()), x, y, w, h, prefix);
            BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(rotateImage, prefix, out);
            //转换后存入数据库
            byte[] b = out.toByteArray();
            FileUtils.uploadFile(b, ConstantConfig.UPLOAD_PATH + sysFile.getUrl());
        } catch (Exception e) {
        	e.printStackTrace();
            throw new Exception("图片裁剪错误！！");
        }
        
        SysUser bean = dao.findById(userId);
        bean.setPicId(sysFile.getId());
        bean.setGmtModified(DateUtils.getCurrentTime());
        if(!bean.update()) {
        	log.warn("修改头像失败。。。");
        }else {
        	if(request!=null) {
        		SysUserUtils.setUser(bean, request);
        	}
		}
	}

	/**
	 * 是否拥有所有权限
	 * @param userId
	 * @return
	 */
	public boolean isSuper(Long userId){
		String sql = "SELECT COUNT(a.id) from sys_role a " +
				"INNER JOIN sys_user_role b on b.role_id = a.id " +
				"where a.is_super = 1 and b.user_id = "+userId;
		Integer count = Db.queryInt(sql);
		if(count!=null && count.intValue()>0){
			return true;
		}
		return false;
	}

	public Set<String> getUserPerms(Long userId){
		Set<String> perms = new HashSet<>();
		//查询是否拥有所有权限
		if(isSuper(userId)){
			perms.add("*");
		}else{
			//查询用户所有权限
			String sql = "SELECT DISTINCT c.perms FROM sys_user_role a " +
					"INNER JOIN sys_role_menu b on b.role_id=a.role_id " +
					"INNER JOIN sys_menu c on c.id = b.menu_id " +
					"where a.user_id = "+userId;

			List<Object> query = Db.query(sql);
			for (Object obj : query){
				if (!com.zirenx.utils.StringUtils.isEmpty(obj)){
					perms.add(obj.toString());
				}
			}
		}
		return perms;
	}
}
